package com.manopservice.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.manopservice.model.CarModel;
import com.manopservice.model.CarPart;
import com.manopservice.model.ResultPagination;

@Repository("carPartDAO")
public class CarPartDAOImpl implements CarPartDAO{
	
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void save(CarPart carPart) {
		sessionFactory.getCurrentSession().saveOrUpdate(carPart);
		
	}
	
	@Override
	public void delete(int id) {
		CarPart carPart = (CarPart) sessionFactory.getCurrentSession().get(CarPart.class, id);
		sessionFactory.getCurrentSession().delete(carPart);	
	}

	@SuppressWarnings("unchecked")
	public List<CarPart> findAll() {
		
		return (List<CarPart>) sessionFactory.getCurrentSession().createCriteria(CarPart.class).list();
	}

	@Override
	public CarPart findById(int id) {
		return (CarPart) sessionFactory.getCurrentSession().get(CarPart.class, id);
	}

	@SuppressWarnings("unchecked")
	public ResultPagination<List<CarPart>> findByModel(String modelName, int pageSelect, int paging) {
		
		List<CarModel> listCarModel = sessionFactory.getCurrentSession().createCriteria(CarModel.class).add(Restrictions.eq("nameEng", modelName)).list();
		CarModel carModel = new CarModel();
		if(listCarModel!=null){
			java.util.Iterator<CarModel> carModelIter = listCarModel.iterator();
			
			while(carModelIter.hasNext()){
				carModel = (CarModel) carModelIter.next();
			}
		}else{
			System.out.println("There is no data");
		}
		
		ResultPagination<List<CarPart>> result = new ResultPagination<List<CarPart>>();
		
		/*Count Data*/
		
		Criteria criteriaCount = sessionFactory.getCurrentSession().createCriteria(CarPart.class);
		criteriaCount.add(Restrictions.eq("carModel", carModel));
		criteriaCount.setProjection(Projections.rowCount());
		int countResult = Integer.parseInt(criteriaCount.list().get(0).toString());
	
		
		/*Function Math.ceil use for round up result of double*/
		int amountPages = (int) Math.ceil((double) countResult/paging);
		
		result.setCountResult(countResult);
		result.setAmountPages(amountPages);

		/*Calculate the first of result by page select*/		
		int firstResult = pageSelect > 1 ? paging * (pageSelect-1) : 0;
					
		/*Paging Data*/
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(CarPart.class);
		criteria.add(Restrictions.eq("carModel", carModel));		
		criteria.setMaxResults(paging);
		criteria.setFirstResult(firstResult);
		
		result.setEntityClass(criteria.list());
				
		return result;
	}

}
